import React, { Component } from 'react'
import axios from 'axios'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { connect } from 'dva'
import {
  Card,
  Tooltip,
  Button,
  Form,
  Input,
  Select,
  DatePicker,
  Spin,
  Row,
  Col,
  Tabs,
  Pagination,
  Modal,
  InputNumber,
  Icon,
  Upload,
  Radio,
  message
} from 'antd'
import MyPageTable from '@/components/MyPageTable'
import OrderService from '@/services/order'
import { getTimeDistance } from '@/utils/utils'
import moment from 'moment'
import { orderStatusMap } from '@/utils/enum'
import ExportJsonExcel from "js-export-excel";
function getToken() {
  const token = localStorage.getItem('business-token')
  return token
}
const { Option } = Select
const { RangePicker } = DatePicker

@connect(({ order, loading }) => ({
  ...order,
  loading: loading.effects['order/rentOrderPageList']
}))
@Form.create()
export default class HomePage extends Component {
  state = {
    current: 1,
    pageSize: 10,
    orderId: null,
    datas: {},
    orderVisible: '',
    loading: false,
    yunTime: getTimeDistance('month')
  }

  columns = [
    {
      title: '订单ID',
      dataIndex: 'original_order_no',
      align: 'center',
      width: '120px'
    },
    {
      title: '下单时间',
      dataIndex: 'orderCreateTime',
      align: 'center',
      width: '150px'
    },
    {
      title: '逾期期数',
      align: 'center',
      width: '100px',
      render: (text, record) => (
        <span style={{color: 'red'}}>{record.overDuePeriods}</span>
      )
    },
    {
      title: '手机号',
      dataIndex: 'telephone',
      align: 'center',
      width: '130px'
    },
    {
      title: '所购商品',
      align: 'center',
      dataIndex: 'name',
      width: '200px'
    },
    {
      title: '收货人',
      align: 'center',
      dataIndex: 'realname',
      width: '100px'
    },
    {
      title: '收货地址',
      align: 'center',
      dataIndex: 'street',
      width: '200px'
    },
    {
      title: '发货时间',
      dataIndex: 'delivery_time',
      align: 'center',
      width: '150px'
    },
    {
      title: '快递单号',
      align: 'center',
      dataIndex: 'express_no',
      width: '160px'
    },
    {
      title: '串码',
      align: 'center',
      dataIndex: 'imei_sn',
      width: '150px'
    },
    {
      title: '进货价',
      align: 'center',
      width: '80px',
      dataIndex: 'purchase_price'
    },
    {
      title: '状态',
      align: 'center',
      width: '80px',
      render: (text, record) => (
        <span>{orderStatusMap[record.order_status]}</span>
      )
    },
    {
      title: '操作',
      align: 'center',
      width: '60px',
      render: (text, record) => (
        <span>
          <Button
            type="link"
            size="small"
            onClick={() => this.goDetail(record)}
          >
            详情
          </Button>
          {
            (record.status == '04' && record.imei_sn && record.purchase_price) ?
            (
              <Button
                type="primary"
                size="small"
                onClick={() => this.onPaster(record)}
              >
                发货
              </Button>
            )
            : null
          }
        </span>
      )
    }
  ]

  componentDidMount() {
    this.onList(1, 10)
  }

  goDetail = async data => {
    window.open(`/#/task/order/detail?id=${data.original_order_no}`)
  }
  // 查询订单列表
  onList = (pageNumber, pageSize, data = {}) => {
    this.setState({loading: true});
    const { dispatch } = this.props
    this.setState({
      current: pageNumber
    })

    dispatch({
      type: 'order/rentOrderPageList',
      payload: {
        pageSize,
        pageNumber,
        dueOrder: 1,
        dueUnPay: 1,
        ...data
      }
    }).then((e => {
      this.setState({loading: false});
    }))
  }

  // 重置
  handleReset = e => {
    this.props.form.resetFields()
    this.handleSubmit(e)
  }

  // 表单查询
  handleSubmit = e => {
    e && e.preventDefault()
    this.props.form.validateFields(
      ['username', 'phone', 'originalOrderNo', 'createDate','dueUnPay'],
      (err, values) => {
        if (values.createDate && values.createDate.length < 1) {
          values.startTime = ''
          values.endTime = ''
          this.setState(
            {
              datas: { ...values }
            },
            () => {
              this.onList(1, 10, { ...values})
            }
          )
        } else if (values.createDate) {
          values.startTime = moment(values.createDate[0]).format(
            'YYYY-MM-DD HH:mm:ss'
          )
          values.endTime = moment(values.createDate[1]).format(
            'YYYY-MM-DD HH:mm:ss'
          )
          this.setState(
            {
              datas: { ...values }
            },
            () => {
              this.onList(1, 10, { ...values})
            }
          )
        } else {
          this.setState(
            {
              datas: { ...values }
            },
            () => {
              this.onList(1, 10, { ...values})
            }
          )
        }
      }
    )
  }

  // onexport = () => {
  //   let sheetFilter = ['create_time', 'original_order_no', 'name','spec','realname','telephone','street','express_no','imei_sn','purchase_price']
  //       let option = {
  //           fileName: '需补充物流信息（完善物流单号、串码、进货价、是否入池）', // 导出默认文件名
  //           datas: [
  //               {
  //                   sheetData: this.props.allList, // 保存至表格的数据
  //                   sheetFilter: sheetFilter,
  //                   sheetHeader: ['创建时间', '订单号', '产品名称','规格','收件人','电话','地址','物流单号','串码','进货价'], // 表格-表头
  //                   columnWidths: ['10', '18', '20','20','6','8','20','8','8','6','5'], // 单元格宽度
  //               },
  //           ]
  //       }
  //       var toExcel = new ExportJsonExcel(option) // 创建新的模板
  //       toExcel.saveExcel() 
  // }

  // onimport = file => {
  //   let formdata = new FormData()
  //   formdata.append('file', file)
  //   axios(`/hzsx/order/rentOrders/orderImeiSnBatchUpdate`, {
  //     method: 'POST',
  //     headers: { token: getToken() },
  //     data: formdata
  //   }).then(res => {
  //     if (res.data.responseType === 'SUCCESS') {
  //       this.onPage({
  //           current: this.state.current,
  //           pageSize: this.state.pageSize
  //       })
  //       message.success('导入成功~')
  //     } else {
  //       message.error('导入失败')
  //     }
  //   })
  // }

  // table 页数
  onPage = e => {
    this.setState(
      {
        current: e.current,
        pageSize: e.pageSize
      },
      () => {
        const params = {
          ...this.state.datas
        }
        this.onList(e.current, e.pageSize, params)
      }
    )
  }

  //打印面单机
  onPaster = async data => {
    this.setState({loading: true});
    let res = await  OrderService.createExpressNo({
      orderId: data.original_order_no,
      imeiSn: data.imei_sn
    });
    if(res){
      this.deliver(res, data.original_order_no, data.purchase_price); //发货
    }else{
      message.error('面单机打印失败～')
    }
    this.setState({loading: false});
  }

  //  发货
  deliver = async (expressNo,orderId,purchasePrice) => {
    this.setState({loading: true});
    OrderService.orderDelivery({
      expressId: 7,
      logisticsFileUrl: '',
      expressNo,
      purchasePrice,
      orderId
    }).then(() => {
      message.success('发货成功~')
      this.onPage({
          current: this.state.current,
          pageSize: this.state.pageSize
      })
      this.setState({loading: false});
    }).catch(() => {
      message.error('发货失败～')
      this.setState({loading: false});
    })
  }


  render() {
    const { allList, allTotal, form } = this.props
    const paginationProps = {
      showSizeChanger: true,
      current: this.state.current,
      pageSize: this.state.pageSize,
      total: allTotal,
      showTotal: total => (
        <span style={{ fontSize: '14px' }}>
          <span>共{Math.ceil(total / 10)}页</span>&emsp;
          <span>共{total}条</span>
        </span>
      )
    }
    const { getFieldDecorator } = form

    return (
      <PageHeaderWrapper>
        <Card bordered={false}>
          <Form
            style={{ paddingBottom: '30px' }}
            layout="inline"
            onSubmit={this.handleSubmit}
          >
            <Form.Item label="下单人姓名">
              {getFieldDecorator(
                'username',
                {}
              )(<Input allowClear placeholder="请输入下单人姓名" />)}
            </Form.Item>

            <Form.Item label="下单人手机号">
              {getFieldDecorator(
                'phone',
                {}
              )(<Input allowClear placeholder="请输入下单人手机号" />)}
            </Form.Item>

            <Form.Item label="订单编号">
              {getFieldDecorator(
                'originalOrderNo',
                {}
              )(<Input allowClear placeholder="请输入订单编号" />)}
            </Form.Item>
            {/* <Form.Item label="创建时间">
              {getFieldDecorator('createDate', {})(<RangePicker />)}
            </Form.Item> */}
            <Form.Item label="还款状态">
              {getFieldDecorator('dueUnPay', {
                  initialValue: 1,
              })(
                <Select
                  placeholder="是否还款"
                  allowClear
                  style={{ width: 180 }}
                >
                <Option value={0} key={0}>
                  已还
                </Option>
                <Option value={1} key={1}>
                  未还
                </Option>
                </Select>
              )}
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button htmlType="button" onClick={this.handleReset}>
                重置
              </Button>
              {/* <Button onClick={this.onexport} style={{marginRight: "10px"}}>物流信息模版导出</Button> */}
              {/* <Upload
                  beforeUpload={file => {
                    this.onimport(file)
                    return false
                  }}
                  multiple={false}
                  showUploadList={false}
                  maxCount={1}
                >
                  <Button type="primary" ghost>
                    <Icon type="upload" /> 物流信息导入
                  </Button>
                </Upload> */}
            </Form.Item>
          </Form>
          {/* 状态控制栏 */}
          <Spin spinning={this.state.loading}>
            {/* 订单列表 */}
            <MyPageTable
              scroll
              onPage={this.onPage}
              paginationProps={paginationProps}
              dataSource={allList}
              columns={this.columns}
            />
          </Spin>
        </Card>
      </PageHeaderWrapper>
    )
  }
}
